<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片试图区域 -->
    <el-card>
      <!-- 输入和添加区域 -->

      <el-row :gutter="10">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryParams.query" clearable @clear="__getUsers">
            <el-button slot="append" icon="el-icon-search" @click="__getUsers"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="AddUserDialogVisible = !AddUserDialogVisible">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="姓名"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column label="状态">
          <!-- 使用插槽喧嚷组件 -->
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="handleUserStateChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <!-- 文本提示 -->
            <el-tooltip content="编辑" placement="top" :enterable="false">
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="editUserDialogShowClcik(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top" :enterable="false">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="handleDeleteUser(scope.row.id)"
              ></el-button>
            </el-tooltip>
            <el-tooltip content="分配角色" placement="top" :enterable="false">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 页码区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pagenum"
        :page-sizes="[2,3, 5, 7]"
        :page-size="100"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <!-- 添加用户提示框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="AddUserDialogVisible"
        width="50%"
        @close="addFormDialogClosed"
      >
        <!-- 内容主体区 -->
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="80px">
          <el-form-item label="用户名称" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="用户密码" prop="password">
            <el-input v-model="addForm.password"></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="AddUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserConfirm">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑用户提示框 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editUserDialogVisible"
        width="50%"
        @close="editFormDialogClosed"
      >
        <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
          <el-form-item label="用户名称">
            <el-input v-model="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserConfirm">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色框 -->
      <el-dialog title="修改用户角色" :visible.sync="setRoleDialogVisible" width="50%" @close='setRoleDialogClosed'>
        <div>
          <p>当前的用户: {{userinfo.username}}</p>
          <p>当前的角色: {{userinfo.role_name}}</p>
          <p>
            分配新角色
            <el-select v-model="selectedRoleId" placeholder="请选择">
              <el-option
                v-for="item in roleList"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              ></el-option>
            </el-select>
          </p>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="setRoleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="handleSaveRoleInfo">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  created() {
    // 获取用户列表
    this.__getUsers()
  },
  data() {
    // 自定义邮箱的校验规则
    const checkEmail = (rule, value, callback) => {
      const regEmail = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法邮箱'))
    }
    // 定义手机号码正则
    const checkMobile = (rule, value, callback) => {
      const regMobile = /^1(3|4|5|6|7|8|9)\d{9}$/
      if (regMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入合法手机号码'))
    }
    return {
      userlist: [], // 用户列表数据
      queryParams: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      total: 0, // 用户列表总数
      AddUserDialogVisible: false, // 新增用户提示框
      editUserDialogVisible: false, // 编辑用户提示框
      addForm: {
        username: '',
        email: '',
        mobile: ''
      },
      // 新增用户校验规则
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名称', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '用户名称长度应在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          {
            min: 6,
            max: 16,
            message: '用户密码长度应在 6 到 16 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 编辑用户 对象
      editForm: {},
      // 编辑用户正则验证
      editFormRules: {
        email: [
          { required: true, message: '请输入用户邮箱', trigger: 'blur' },
          { validator: checkEmail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 修改用户角色的提示框
      setRoleDialogVisible: false,
      // 需要被分配角色的用户信息
      userinfo: {},
      //  所有角色的数据列表
      roleList: [],
      // 选中的用户角色
      selectedRoleId: ''
    }
  },
  methods: {
    // -------------- 发送网络请求 ------------------
    async __getUsers() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryParams
      })
      if (res.meta.status !== 200) return this.$showToast.error(res.meta.msg)
      this.total = res.data.total
      this.userlist = res.data.users
    },
    //  ----------------- 事件监听 --------------------
    handleSizeChange(currentPage) {
      this.queryParams.pagesize = currentPage
      this.__getUsers()
    },
    handleCurrentChange(currentPage) {
      this.queryParams.pagenum = currentPage
      this.__getUsers()
    },
    // switch 发生改变
    async handleUserStateChange(rowVal) {
      const { data: res } = await this.$http.put(
        `users/${rowVal.id}/state/${rowVal.mg_state}`
      )
      if (res.meta.status !== 200) {
        return this.$showToast.error('更新用户状态失败')
      }

      this.$showToast.success('更新用户状态成功')
    },
    // 监听添加用户提示框关闭, 并清空用户填写信息和验证结果
    addFormDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    // 点击确定添加新用户
    addUserConfirm() {
      // 1. 先判断表单是否通过验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return false
        }

        const { data: res } = await this.$http.post('users', this.addForm)

        if (res.meta.status !== 201) {
          return this.$showToast.error('用户添加失败')
        }
        this.$showToast.success('添加用户成功')
        // 关闭添加用户框
        this.AddUserDialogVisible = false
        // 用心获取数据渲染页面
        this.__getUsers()
      })
    },
    // 点击编辑用户按钮
    async editUserDialogShowClcik(userid) {
      // 点击根据用户ID获取该用户的信息
      const { data: res } = await this.$http.get(`users/${userid}`)
      this.editForm = res.data
      if (res.meta.status !== 200) {
        return this.$showToast.error('用户查询失败')
      }
      this.editUserDialogVisible = true
    },
    // 关闭编辑框,清空数据和验证
    editFormDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 点击用户编辑确认按钮
    editUserConfirm() {
      this.$refs.editFormRef.validate(async vaild => {
        // 1. 先判断表单是否通过验证
        if (!vaild) {
          return false
        }

        const { email, mobile } = this.editForm

        const { data: res } = await this.$http.put(
          `users/${this.editForm.id}`,
          {
            email,
            mobile
          }
        )

        if (res.meta.status !== 200) {
          return this.$showToast.error('更新数据失败')
        }

        this.$showToast.success('更新数据成功')
        this.editUserDialogVisible = false
        this.__getUsers()
      })
    },
    // 点击删除按钮 删除用户信息
    async handleDeleteUser(userid) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      if (confirmResult === 'confirm') {
        const { data: res } = await this.$http.delete(`users/${userid}`)
        if (res.meta.status !== 200) {
          return this.$showToast.error('删除失败')
        }
        this.$showToast.success('删除成功')
        this.__getUsers()
      } else {
        this.$showToast.info('已取消删除')
      }
    },
    // 点击分配角色
    async setRole(userinfo) {
      this.userinfo = userinfo
      // 在弹框之前先获取所有角色列表数据
      const { data: res } = await this.$http.get('roles')

      if (res.meta.status !== 200) {
        return this.$showToast.error('获取角色数据失败')
      }
      this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    // 点击确定按钮分配角色
    async handleSaveRoleInfo() {
      if (!this.selectedRoleId) {
        return this.$showToast.error('请选择要分配的角色')
      }
      // 将选中角色的id发送过去
      const { data: res } = await this.$http.put(
        `users/${this.userinfo.id}/role`,
        {
          rid: this.selectedRoleId
        }
      )
      if (res.meta.status !== 200) {
        this.$showToast.error('更新用户角色失败')
      }

      this.$showToast.success('更新用户角色成功')
      this.__getUsers()
      this.setRoleDialogVisible = false
    },
    // 监听用户角色框关闭
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userinfo = {}
    }
  }
}
</script>

<style>
</style>
